package com.lill.support.aspect;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;

import org.apache.shiro.SecurityUtils;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.multipart.support.MissingServletRequestPartException;

import com.lill.support.annotation.CurrentUser;
import com.lill.system.model.SysUserEntity;

@Component
public class CurrentUserParamResolver implements HandlerMethodArgumentResolver {

	public boolean supportsParameter(MethodParameter parameter) {
		return parameter.getParameterType().isAssignableFrom(SysUserEntity.class)&&parameter.hasParameterAnnotation(CurrentUser.class);
	}

	public Object resolveArgument(MethodParameter parameter,ModelAndViewContainer mavContainer, NativeWebRequest webRequest,WebDataBinderFactory binderFactory) throws Exception {
		Object userObj=SecurityUtils.getSubject().getPrincipal();
		if(null!=userObj){
			SysUserEntity user=new SysUserEntity();
			
			BeanInfo bean = Introspector.getBeanInfo(SysUserEntity.class);
			BeanInfo beanObj = Introspector.getBeanInfo(userObj.getClass());
			PropertyDescriptor[] pds = bean.getPropertyDescriptors();
			PropertyDescriptor[] pdsObj = beanObj.getPropertyDescriptors();
			
			String propertyName=null;
			Object pdsObjVal=null;
			for (int i = 0; i < pds.length; i++) {
				propertyName=pds[i].getName();
				if(!"class".equals(propertyName)){
					for (int j = 0; j < pdsObj.length; j++) {
						if(propertyName.equals(pdsObj[j].getName())){
							pdsObjVal=pdsObj[j].getReadMethod().invoke(userObj);
						}
					}
					pds[i].getWriteMethod().invoke(user, pdsObjVal);
//					pds[i].getWriteMethod().invoke(user, new PropertyDescriptor(propertyName, userObj.getClass()).getReadMethod().invoke(userObj));
				}
			}
			return user;
		}
        throw new MissingServletRequestPartException("currentUser");
	}

}
